/**
 * 
 */
package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.CountryDAO;
import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.domain.City;
import org.arpit.masteringextjs.domain.Country;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

/**
 * @author arpit
 *
 */
public class CountryDAOImpl implements CountryDAO{

	private static CountryDAO actorDAO;
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private CountryDAOImpl () {
		
	}
	
	public static CountryDAO getInstance() {
		if(actorDAO == null) {
			actorDAO = new CountryDAOImpl();
		}
		return actorDAO;
	}
	
	@Override
	public List<Country> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Country.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<Country> actors = crit.list();
		session.getTransaction().commit();
		session.close();
		return actors;
	}

	@Override
	public Country create(Country actor) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Country createdActor = (Country) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return createdActor;
	}

	@Override
	public Country update(Country country) {
		if(country.getId() == null || country.getId() == 0) {
			throw new IllegalArgumentException("Invalid data");
		}
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Country updateCountry = (Country) session.merge(country);
		session.getTransaction().commit();
		session.close();
		return updateCountry;
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Country.class);
		crit.add(Restrictions.eq("id", id));
		List<Country> countries = crit.list();
		if(countries.isEmpty()) {
			throw new IllegalArgumentException("Country with id " + id +" not found");
		}
		Country country = countries.get(0);
		session.delete(country);
		session.getTransaction().commit();
		session.close();
	}

}
